package com.shu.intercepter;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截器
 * @author shujinhao
 */
@Component
public class TimeInterceptor implements HandlerInterceptor {
    //访问之前
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        System.out.println("preHandle");

        System.out.println(((HandlerMethod)o).getBean().getClass().getName());
        System.out.println(((HandlerMethod)o).getMethod().getName());

        httpServletRequest.setAttribute("startTime",System.currentTimeMillis());
        //返回结果决定是否执行方法
        return true;
    }

    //发生异常不会调用
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
        Long startTime = (Long) httpServletRequest.getAttribute("startTime");
        System.out.println("postHandle 耗时" + (System.currentTimeMillis()-startTime));


    }

    //访问之后,不管是否发生异常都会调用
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        System.out.println("afterCompletion");
        Long startTime = (Long) httpServletRequest.getAttribute("startTime");

        System.out.println("afterCompletion 耗时" + (System.currentTimeMillis()-startTime));
        System.out.println(e);

    }
}
